package com.wzf.greattruth.dubbo.tester;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

/**
 * 此示例启动一批线程向文件中写数据，等待另外一个线程读取写入的数据并返回一个信息,主要的目的是模拟一个多线程环境下的读写
 * @author wuzhengfei
 *
 */
public class ConcurrentRWTester {
	private static final String DIR = "/home/admin/log";
	
	private static final int max = 10000;
	private static final int timeout = 1000 * 10;

	private static final Map<Integer, Request> map = new ConcurrentHashMap<>();

	public static void main(String[] args) throws IOException {
		File folder = new File(DIR);
		File[] files = folder.listFiles();
		for( File file : files ){
			file.delete();
		}
		
		File file = new File(folder, "rpc.txt");
		
		
		final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));  
		int total = 100;
		final Random random = new Random();
		for (int i = 0; i < total; i++) {
			final int index = i;
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					String message = "req_" + random.nextInt(max);
					int id = index;
					Request request = new Request();
					request.setId(id);
					request.setMessage(message);

					try {
						writer.write(request.toString());
						writer.write("\r\n");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					
					map.put(id, request);
					Future future = new Future(request, timeout);
					String result = null;
					try {
						result = (String) future.get();
					} catch (Exception e) {
						System.err.println(
								"future.get() failed!  id=" + id + "  message=" + message + "  e=" + e.getMessage());
					}
					System.err.println("id=" + id + "  message=" + message + "   result=" + result);
				}
			});
			t.start();
		}
		
		
		try {
			Thread.currentThread().sleep(1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		writer.close();
		
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); 
		
		String line = null ;
        while((line = reader.readLine()) != null){
        	if( StringUtils.isBlank(line) ){
        		continue ;
        	}
        	String[] items = line.split(",");
        	Request request = new Request() ;
        	request.setId(Integer.parseInt(items[0]));
        	request.setMessage(items[1]);
        	Response response = new Response() ;
			response.setId(request.getId());
			response.setMessage("response____"+ request.getMessage());
			Future.received(response);
        }  
        reader.close();
	}

}
